package Servlet;

import com.cyy.bean.history;
import com.cyy.bean.record;
import com.cyy.dao.cartDao;
import com.cyy.dao.historyDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

@WebServlet("/changeCartToHistory")
public class changeCartToHistoryServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String userName=request.getSession().getAttribute("name").toString();
        cartDao cartDao = new cartDao();
        historyDao historyDao=new historyDao();
        ArrayList<record> carts=null;
//        获得购物车内没有下架的商品
        try {
            carts = cartDao.selectAll(userName,1);
        } catch (SQLException | ClassNotFoundException throwables) {
            throwables.printStackTrace();
        }
//        从购物车中移除这些商品
        try {
            cartDao.deleteAll(userName);
        } catch (SQLException | ClassNotFoundException throwables) {
            throwables.printStackTrace();
        }
        if (carts != null) {
            String productName="";
            int state=0;
            int price=0,num=0,usability;
//            获得下单时间
            Date date = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String dateTime = df.format(date);
            for(int i=0;i<carts.size();i++)
            {
                productName=carts.get(i).getProductName();
                price=carts.get(i).getPrice();
                num=carts.get(i).getNum();
                usability=carts.get(i).getUsability();
                if(usability==0)
                {
                    System.out.println(productName+" 已经下架,无法购买！");
                }
                else {
                    try {
//                        将这些商品加入到购买历史记录
                        historyDao.add(new history(0, userName, productName, price, num, dateTime, state, usability));
                    } catch (SQLException | ClassNotFoundException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
        }
        request.getRequestDispatcher("/showHistory").forward(request,response);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
